package ui;

import java.awt.Color;

import javax.swing.BorderFactory;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

/**
 * Modal dialog that prevents interaction with GoViewer while an
 * SGF file is being edited in an external program.
 * @author TKington
 *
 */
public class EditingSGFDialog extends JDialog {
	/**
	 * Creates a new EditingSGFDialog.
	 * @param parent the parent frame
	 * @param sgfEditProcess the Process of the external editing program
	 */
	public EditingSGFDialog(JFrame parent, Process sgfEditProcess) {
		super(parent, true);
		
		new WaitingThread(sgfEditProcess).start();

		setUndecorated(true);
		
		JPanel panel = new JPanel();
		panel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
		panel.add(new JLabel("Close the SGF editor to continue..."));
		add(panel);
		
		pack();
		setLocationRelativeTo(parent);
		setVisible(true);
	}
	
	/**
	 * Callback that notifies this object that the external program
	 * has been closed.
	 *
	 */
	private void procDone() {
		setVisible(false);
	}
	
	/**
	 * Thread that waits for the external process to exit.
	 *
	 */
	private class WaitingThread extends Thread {
		/** Handle to the external process. */
		private Process proc;
		
		/**
		 * Creates a WaitingThread that will wait for the external
		 * process to exit.
		 * @param proc handle to the external process
		 */
		public WaitingThread(Process proc) {
			this.proc = proc;
		}
		
		@Override
		public void run() {
			try { proc.waitFor(); } catch(InterruptedException e) { /* */ }
			
			SwingUtilities.invokeLater(new Runnable() {
				public void run() {
					procDone();
				}
			});
		}
	}
}
